package com.jweb.framework.http.submit;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.jweb.framework.core.ContextEx;
import com.jweb.framework.core.CoreException;
import com.jweb.framework.core.CoreRuntimeException;
import com.jweb.framework.core.channel.ChannelContext;
import com.jweb.framework.http.interceptors.ServletChannelInterceptor;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：FORM表单重复提交验证
 */
public class ValidateFormSubmitInterceptor<Request, Response> implements ServletChannelInterceptor<Request, Response> , InitializingBean {
	
	protected static Logger logger = LoggerFactory.getLogger(ValidateFormSubmitInterceptor.class);
	private Properties submits ;
	private Map<String, String> maps = new HashMap<String, String>();
	
	public void setSubmits(Properties submits) {
		this.submits = submits;
	}

	@Override
	public void onRequest(ChannelContext<Request, Response> channelContext,
			ContextEx ctxEx) throws CoreException {
		String processId = ctxEx.getProcessId();
		if(this.maps.containsKey(processId)&&this.maps.containsValue("dupsubmit")) { // 防重复提交 
			if(isDupSubmit((HttpServletRequest) channelContext.getRequest())){
				logger.info("{}：请求重复提交!" , processId);
				throw new CoreRuntimeException("JAVAHT0100", processId+"：请求，表单重复提交!");
			}
		}
	}

	@Override
	public void onResponse(ChannelContext<Request, Response> channelContext,
			ContextEx ctxEx, Throwable throwable) {
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Iterator<String> it = this.submits.stringPropertyNames().iterator();
		while(it.hasNext()){
			String key = it.next();
			String value = this.submits.getProperty(key);
			this.maps.put(key, value);
		}
	}
	
	/**
	 * 判断是否重复提交
	 * @param request
	 * @return
	 */
	private boolean isDupSubmit(HttpServletRequest request) {
		String clientToken = request.getParameter("token");
		if(clientToken == null){
			return true ;
		}
		
		String serverToken = (String) request.getSession(false).getAttribute("token");
		logger.debug("serverToken: " + serverToken + " clientToken: " + clientToken);
		if(serverToken == null){
			return true ;
		}
		
		if(!serverToken.equals(clientToken)){
			return true ;
		}
		
		request.getSession().removeAttribute("token");
		return false ;
	}

}
